import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

/// SharedPreferences 工具类
class SpUtil {
  static SharedPreferences? _prefs;
  static String? _currentUid;

  /// 初始化，在app启动时调用
  static Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
    _currentUid = getStoredUid();  // 恢复存储的uid
  }

  /// 设置当前用户ID
  static void setCurrentUid(String uid) {
    _currentUid = uid;
  }

  /// 清除当前用户ID
  static void clearCurrentUid() {
    _currentUid = null;
  }

  /// 获取完整的key（用户相关的key会自动拼接uid）
  static String _getKey(String key, {bool withUid = true}) {
    if (withUid && _currentUid != null) {
      return '${_currentUid}_$key';
    }
    return key;
  }

  // 字符串相关操作
  static Future<bool> setString(String key, String value, {bool withUid = true}) async {
    return await _prefs?.setString(_getKey(key, withUid: withUid), value) ?? false;
  }

  static String? getString(String key, {bool withUid = true}) {
    return _prefs?.getString(_getKey(key, withUid: withUid));
  }

  // 布尔值相关操作
  static Future<bool> setBool(String key, bool value, {bool withUid = true}) async {
    return await _prefs?.setBool(_getKey(key, withUid: withUid), value) ?? false;
  }

  static bool? getBool(String key, {bool withUid = true}) {
    return _prefs?.getBool(_getKey(key, withUid: withUid));
  }

  // 整数相关操作
  static Future<bool> setInt(String key, int value, {bool withUid = true}) async {
    return await _prefs?.setInt(_getKey(key, withUid: withUid), value) ?? false;
  }

  static int? getInt(String key, {bool withUid = true}) {
    return _prefs?.getInt(_getKey(key, withUid: withUid));
  }

  // 双精度相关操作
  static Future<bool> setDouble(String key, double value, {bool withUid = true}) async {
    return await _prefs?.setDouble(_getKey(key, withUid: withUid), value) ?? false;
  }

  static double? getDouble(String key, {bool withUid = true}) {
    return _prefs?.getDouble(_getKey(key, withUid: withUid));
  }

  // 字符串列表相关操作
  static Future<bool> setStringList(String key, List<String> value, {bool withUid = true}) async {
    return await _prefs?.setStringList(_getKey(key, withUid: withUid), value) ?? false;
  }

  static List<String>? getStringList(String key, {bool withUid = true}) {
    return _prefs?.getStringList(_getKey(key, withUid: withUid));
  }

  // 删除指定key的数据
  static Future<bool> remove(String key, {bool withUid = true}) async {
    return await _prefs?.remove(_getKey(key, withUid: withUid)) ?? false;
  }

  // 清除当前用户的所有数据
  static Future<void> clearUserData() async {
    if (_currentUid == null) return;
    
    final allKeys = _prefs?.getKeys() ?? Set();
    for (var key in allKeys) {
      if (key.startsWith('${_currentUid}_')) {
        await _prefs?.remove(key);
      }
    }
  }

  // 清除所有数据
  static Future<bool> clearAll() async {
    return await _prefs?.clear() ?? false;
  }

  // 获取所有key
  static Set<String> getKeys() {
    return _prefs?.getKeys() ?? Set();
  }

  // 判断是否包含某个key
  static bool containsKey(String key, {bool withUid = true}) {
    return _prefs?.containsKey(_getKey(key, withUid: withUid)) ?? false;
  }

  static const String _uidKey = 'current_uid';  // uid的存储key

  /// 保存uid到SP并设置为当前uid
  static Future<bool> saveUid(String uid) async {
    final result = await _prefs?.setString(_uidKey, uid) ?? false;
    if (result) {
      _currentUid = uid;
    }
    return result;
  }

  /// 从SP获取保存的uid
  static String? getStoredUid() {
    return _prefs?.getString(_uidKey);
  }

  /// 清除存储的uid
  static Future<bool> clearStoredUid() async {
    _currentUid = null;
    return await _prefs?.remove(_uidKey) ?? false;
  }

  // 通用List相关操作
  static Future<bool> setList(String key, List<dynamic> value, {bool withUid = true}) async {
    try {
      final String jsonString = json.encode(value);
      return await setString(_getKey(key, withUid: withUid), jsonString);
    } catch (e) {
      print('Error saving list: $e');
      return false;
    }
  }

  static List<dynamic>? getList(String key, {bool withUid = true}) {
    try {
      final String? jsonString = getString(_getKey(key, withUid: withUid));
      if (jsonString == null) return null;
      return json.decode(jsonString) as List<dynamic>;
    } catch (e) {
      print('Error reading list: $e');
      return null;
    }
  }
} 